package com.ziyucoding.springboot.labs.lab11.netty.demo1;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * 客户端处理器
 *
 * @author ziyucoding
 * @date 2022-11-09
 **/
public class ClientHandler {

    /**
     * 最大数据长度
     */
    public static final int MAX_DATA_LEN = 1024;

    private final Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    /**
     * 启动
     *
     * @return void
     **/
    public void start() {
        System.out.println("客户端接入");
        new Thread(new Runnable() {
            @Override
            public void run() {
                doStart();
            }
        }).start();
    }

    /**
     * 启动
     *
     * @return void
     **/
    private void doStart() {
        try {
            InputStream inputStream = socket.getInputStream();
            socket.setSoTimeout(5000);
            while (true) {
                byte[] data = new byte[MAX_DATA_LEN];
                int len;
                while ((len = inputStream.read(data)) != -1) {
                    String msg = new String(data, 0, len);
                    System.out.println("客户端传来消息：" + msg);
                    socket.getOutputStream().write(data);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
